package io.renren.wechat.common.aes;

import io.renren.wechat.support.MessageDigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * SHA1 class
 * <p>
 * 计算消息签名接口.
 */
public class SHA1 {

    /**
     * 用SHA1算法生成安全签名
     *
     * @param token     票据
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @param encrypt   密文
     * @return 安全签名
     * @throws AesException aes exception
     */
    public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {

        String[] array = new String[]{token, timestamp, nonce, encrypt};
        StringBuilder sb = new StringBuilder();
        // 字符串排序
        Arrays.sort(array);
        for (int i = 0; i < 4; i++) {
            sb.append(array[i]);
        }
        String str = sb.toString();

        try {
            return getSHA1(str);
        } catch (Exception e) {
            throw new AesException(AesException.ComputeSignatureError);
        }
    }

    public static String getSHA1(String plainText) throws NoSuchAlgorithmException {
        // SHA1签名生成
        MessageDigest md = MessageDigestUtils.getDigest("SHA-1");

        md.update(plainText.getBytes());
        byte[] digest = md.digest();

        StringBuilder hexStr = new StringBuilder();
        String shaHex = "";
        for (byte b : digest) {
            shaHex = Integer.toHexString(b & 0xFF);
            if (shaHex.length() < 2) {
                hexStr.append(0);
            }
            hexStr.append(shaHex);
        }

        return hexStr.toString();
    }
}
